package com.yiren.manager.ctrl.elder;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrElderWalletRechargeRecord;
import com.yiren.entity.YrPaper;
import com.yiren.entity.YrPaperRecord;
import com.yiren.entity.YrStaffInfo;
import com.yiren.manager.form.cost.YrElderWalletRechargeRecordForm;
import com.yiren.manager.form.cost.YrPaperRecordForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.elder.YrElderWalletForm;
import com.yiren.manager.service.iface.cost.YrElderWalletRechargeRecordService;
import com.yiren.manager.service.iface.cost.YrPaperRecordService;
import com.yiren.manager.service.iface.cost.YrPaperService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("elderWallet")
@Controller
public class YrElderWalletController extends YrElderBaseController<YrElderWalletForm, YrElderWallet>{
	
	@Autowired
	private YrElderWalletService selfService;
	
	@Autowired
	private YrStaffInfoService staffInfoService;
	
	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;
	
	@Autowired
	private YrPaperService paperService;
	
	@Autowired
	private YrElderWalletRechargeRecordService elderWalletRechargeRecordService;
	
	@Autowired
	private YrElderService elderService;
	
	@Autowired
	private YrPaperRecordService paperRecordService;
	
	//保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrElderWalletForm> save(String data) throws SwallowException, MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		HTTPResult<YrElderWalletForm> result = new HTTPResult<YrElderWalletForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrElderWalletForm form = tool.mapper("elderWallet", YrElderWalletForm.class);
		if(null==form){
			throwExp("param.error");
		}
		if(null==form.getElderWalletId()||form.getElderWalletId().isEmpty()){
			form.setElderWalletId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
		}
		form.setUpdateTime(new Date());
		YrElderWallet entity = ObjectUtils.objectToObject(form, YrElderWallet.class);
		selfService.save(entity);
		
		return result;
	}
	
	//保存实体
	@RequestMapping("/recharge")
	@ResponseBody
	public HTTPResult<YrElderWalletRechargeRecordForm> recharge(String id,Float money,String updateId) throws Exception{
		HTTPResult<YrElderWalletRechargeRecordForm> result = new HTTPResult<YrElderWalletRechargeRecordForm>();
		if(id==null||money==null||updateId==null){
			throwExp("参数有误");
		}
		YrElderWallet entity = selfService.findOne(id);
		if(null==entity){
			throwExp("查询不到对应的钱包数据");
		}
		String sqlWhere = "elder_id=?1 AND be_status<>2";
		QueryResult<YrElderBeHospital> qrElderBeHospital =elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere, new Object[]{entity.getElderId()});
		if(qrElderBeHospital.getResultList().isEmpty()){
			throwExp("查询不到相关老者住院登记信息");
		}
		YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
		

		YrStaffInfo staffInfo = staffInfoService.findOne(updateId);
		if(null==staffInfo){
			throwExp("updateId有误");
		}
		
		sqlWhere = "staff_id=?1 AND paper_type=2";
		QueryResult<YrPaper> qrPaper = paperService.find(YrPaper.class, sqlWhere, new Object[]{updateId});
		
		if(qrPaper.getResultList().isEmpty()){
			throwExp("暂无该类型的票据号，请先设置");
		}
		
		YrPaper paper = qrPaper.getResultList().get(0);
		
		//增加一条打印记录
		YrPaperRecord paperRecord = costPaperRecord(paper, elderBeHospital.getBeHospitalId(), updateId,
				money, 2);
				
		paper.setUseNum(toNumberStr(paper.getUseNum()));
		entity.setUpdateTime(new Date());
		
		entity.setWalletBalance(entity.getWalletBalance()+money);
		
		// 新增一条钱包充值记录
		YrElderWalletRechargeRecord elderWalletRechargeRecord = new YrElderWalletRechargeRecord();
		elderWalletRechargeRecord.setElderWalletRechargeRecordId(UUIDGenerator.getUUID());
		elderWalletRechargeRecord.setElderId(entity.getElderId());
		elderWalletRechargeRecord.setElderName(entity.getElderName());
		elderWalletRechargeRecord.setElderCarId(entity.getElderCardId());
		elderWalletRechargeRecord.setRechargeMoney(money);
		elderWalletRechargeRecord.setRechargeDate(new Date());
		elderWalletRechargeRecord.setCreateTime(new Date());
		elderWalletRechargeRecord.setCreateId(updateId);
		elderWalletRechargeRecord.setRechargeSource(1);
		elderWalletRechargeRecord.setBeHospitalId(elderBeHospital.getBeHospitalId());
		
		
		Favorites favorites = new Favorites();
		favorites.putFavorite(YrElderWallet.class, entity);
		favorites.putFavorite(YrElderWalletRechargeRecord.class, elderWalletRechargeRecord);
		favorites.putFavorite(YrPaperRecord.class, paperRecord);
		favorites.putFavorite(YrPaper.class, paper);
		
		selfService.executeRecharge(favorites);
		
		ArrayList<YrElderWalletRechargeRecordForm> formList = new ArrayList<YrElderWalletRechargeRecordForm>();
		YrElderWalletRechargeRecordForm rechargeRecordForm = ObjectUtils.objectToObject(elderWalletRechargeRecord, YrElderWalletRechargeRecordForm.class);
		rechargeRecordForm.setWalletBlance(entity.getWalletBalance());
		rechargeRecordForm.setHandler(staffInfo.getName());
		rechargeRecordForm.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital,YrElderBeHospitalForm.class));
		formList.add(rechargeRecordForm);
		
		result.setData(formList);
		
		return result;
	}
	
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrElderWalletForm> find(String searchVal) throws Exception{
		HTTPResult<YrElderWalletForm> result = new HTTPResult<YrElderWalletForm>();
		String sqlWhere = "elder_name=?1 OR elder_card_id=?2";
		
		QueryResult<YrElderWallet> qr = selfService.find(YrElderWallet.class, sqlWhere, new Object[]{searchVal,searchVal});
		
		List<YrElderWalletForm> formList = new ArrayList<YrElderWalletForm>();
		
		for(YrElderWallet entity : qr.getResultList()){
			YrElderWalletForm form = toForm(entity);
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@RequestMapping("findRechargeRecordByDay")
	@ResponseBody
	public HTTPResult<YrElderWalletRechargeRecordForm> findRechargeRecordByDay(String searchVal,String day) throws MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		HTTPResult<YrElderWalletRechargeRecordForm> result = new HTTPResult<YrElderWalletRechargeRecordForm>();
		
		if(searchVal.isEmpty()||day.isEmpty()){
			throwExp("参数有误");
		}
		String sqlWhere = "SELECT a from YrElderWalletRechargeRecord a, YrElder b WHERE b.elderId=a.elderId AND "
				+ "DATE_FORMAT(a.rechargeDate,'%Y-%m-%d')=?1 AND (b.name=?2 OR b.cardId=?2) AND b.elderType=1";
		List<YrElderWalletRechargeRecord> entityList = selfService.findByJPQL(sqlWhere, new Object[] { day, searchVal });
		
		List<YrElderWalletRechargeRecordForm> formList = new ArrayList<YrElderWalletRechargeRecordForm>();
		for(YrElderWalletRechargeRecord entity : entityList){
			YrElderWalletRechargeRecordForm form = ObjectUtils.objectToObject(entity, YrElderWalletRechargeRecordForm.class);
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(entity.getBeHospitalId());
			if(null!=elderBeHospital){
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
			}
			YrElder elder = elderService.findOne(entity.getElderId());
			if(null!=elder){
				form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			}
			sqlWhere = "relation_id=?1 AND paper_type=2 AND be_hospital_id=?2";
			QueryResult<YrPaperRecord> qrPaperRecord = paperRecordService.find(YrPaperRecord.class, sqlWhere,
					new Object[]{entity.getElderWalletRechargeRecordId()+"-walletRecharge",entity.getBeHospitalId()});
			if(!qrPaperRecord.getResultList().isEmpty()){
				YrPaperRecord paperRecord = qrPaperRecord.getResultList().get(0);
				YrPaperRecordForm paperRecordForm = ObjectUtils.objectToObject(paperRecord, YrPaperRecordForm.class);
				form.setPaperRecordForm(paperRecordForm);
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@RequestMapping("balanceRemind")
	@ResponseBody
	public HTTPResult<YrElderWalletForm>  balanceRemind() throws Exception{
		HTTPResult<YrElderWalletForm> result = new HTTPResult<YrElderWalletForm>();
		String sqlWhere = "wallet_balance <= 1500";
		QueryResult<YrElderWallet> qr  = selfService.find(YrElderWallet.class, sqlWhere, new Object[]{});
		List<YrElderWalletForm> formList = new ArrayList<YrElderWalletForm>();
		for(YrElderWallet entity : qr.getResultList()){
			YrElderWalletForm form = toForm(entity);
			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital =elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere, new Object[]{entity.getElderId()});
			if(qrElderBeHospital.getTotalRecord()>0){
				form.setElderBeHospitalId(qrElderBeHospital.getResultList().get(0).getBeHospitalId());;
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@Override
	public YrElderWalletForm toForm(YrElderWallet e) throws Exception {
		YrElderWalletForm form = ObjectUtils.objectToObject(e, YrElderWalletForm.class);
		return form;
	}

	@Override
	public YrElderWallet toEntity(YrElderWalletForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
